package com.gxa.ssm340.controller;

import com.gxa.ssm340.common.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @author Lenovo
 */
@Api(value = "BrandController",tags = "上传接口")
@RestController
public class UploadController {

    @ApiOperation("文件上传")
    @PostMapping("/upload")
    public R upload(String type, MultipartFile file){
        String originalFilename =file.getOriginalFilename();

        //获取文件名,并处理
        //为了保证文件名在服务器中唯一
        //先获取后缀
        String ext = originalFilename.substring(originalFilename.lastIndexOf(".")); //.png
        String fileName = UUID.randomUUID().toString().replaceAll("-", "");

        //创建本地文件
        String root = "d:/img/";

        String destFileName = root+fileName+ext;
        File dest = new File(destFileName);

        //把上传的数据写入到本地文件
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
        }

        //为了让前端可以访问到资源，把路径返回
        return R.success(fileName+ext);
    }
}
